package authorization_code_postgres

import (
	"context"
	"fmt"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/adaptor"
)

type oauth2Route struct {
}

func (r oauth2Route) Init(hertz *server.Hertz) {
	group := hertz.Group("/oauth2")
	group.GET("/authorize", r.authorize())
	group.POST("/token", r.token())
}

func (r oauth2Route) token() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {
		req, err := adaptor.GetCompatRequest(&ctx.Request)
		if err != nil {
			fmt.Println(err)
			return
		}
		// caution: don't pass in c.GetResponse() as it return a copy of response
		rw := adaptor.GetCompatResponseWriter(&ctx.Response)
		err = Oauth2Server.HandleTokenRequest(rw, req)
		if err != nil {
			ctx.JSON(401, err)
		}
	}
}
func (r oauth2Route) authorize() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {
		//var authorize Authorize
		//err := ctx.BindQuery(&authorize)
		//if err != nil {
		//	ctx.JSON(401, err)
		//	return
		//}
		req, err := adaptor.GetCompatRequest(&ctx.Request)
		if err != nil {
			ctx.JSON(401, err)
			return
		}
		fmt.Println(req.URL.String())
		// caution: don't pass in c.GetResponse() as it return a copy of response
		rw := adaptor.GetCompatResponseWriter(&ctx.Response)
		err = Oauth2Server.HandleAuthorizeRequest(rw, req)
		if err != nil {
			ctx.JSON(401, err)
		}
		return
	}
}

type Authorize struct {
	ClientId     string `json:"client_id" query:"client_id"`
	ResponseType string `json:"response_type" query:"response_type"`
	RedirectUri  string `json:"redirect_uri" query:"redirect_uri"`
	State        string `json:"state" query:"state"`
	Scope        string `json:"scope" query:"scope"`
}
